import { HonorTreeData, ListingTreeData, financingTreeData, companyTypeTreeData } from '@/utils/SearchTreeData'

import { HsAdminInput } from '@hs-admin/base-components'

import { Resizable } from 'react-resizable'

import { IndustryChainList } from '@/api/SupplyChain'

import 'react-resizable/css/styles.css'

import { useState, useEffect } from 'react'

import InfiniteScroll from 'react-infinite-scroll-component'

import './search.css'

import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'

import { ServerCheckboxList, ServerAreaSelect, Servertime, SearchData } from '@hs-server/components'

import { Collapse, Button, Empty, Tooltip } from 'antd'

import CompanyAvatar from '@/components/CompanyAvatar'
import { openCompanyDetail } from 'hs-react-company'

const Search = (props: any) => {
  const { success } = props
  const [searchValue, setsearchValue]: any = useState({
    keywords: null,
    trade_plate: null,
    company_type: null,
    time_scope: {
      start_time: null,
      end_time: null
    },
    qualified: null,
    financing_round: null,
    pca: {
      province_column: 'province_code',
      city_column: 'city_code',
      area_column: 'area_code',
      values: []
    }
  })

  const [inputValue, setinputValue]: any = useState('')

  const [filterState, setFilterState] = useState({ width: 350 })

  const [collapsed, setCollapsed] = useState(false)

  const [total, setTotal] = useState(0)

  const [financing_round, setfinancing_round]: any = useState([]) //融资轮次数据

  const [hasMore, setHasMore] = useState(false)

  const [loading, setLoading] = useState(false)

  const [actionindex, setactionindex] = useState(0) //点击左边企业列表激活状态

  const [pagination, setpagination] = useState({
    current: 1,
    pageSize: 8
  })

  //左侧筛选项
  const Collapseitems = [
    {
      key: '1',
      label: '所在地区',
      children: <ServerAreaSelect modelValue={searchValue.pca.values} success={(values: any) => SuccessSearchValue(values, '所在地区')} />,
      extra: genExtra('pca')
    },
    {
      key: '2',
      label: '荣誉资质',
      children: (
        <ServerCheckboxList
          treeData={HonorTreeData}
          modelValue={searchValue.qualified}
          success={(values: any) => SuccessSearchValue(values, 'qualified')}
        />
      ),
      extra: genExtra('qualified')
    },
    {
      key: '3',
      label: '上市情况',
      children: (
        <ServerCheckboxList
          modelValue={searchValue.trade_plate}
          treeData={ListingTreeData}
          success={(values: any) => SuccessSearchValue(values, 'trade_plate')}
        />
      ),
      extra: genExtra('trade_plate')
    },
    {
      key: '4',
      label: '融资阶段',
      children: (
        <ServerCheckboxList
          modelValue={financing_round}
          treeData={financingTreeData}
          success={(values: any) => SuccessSearchValue(values, 'financing_round')}
        />
      ),
      extra: genExtra('financing_round')
    },
    {
      key: '5',
      label: '成立时间',
      children: (
        <div>
          <div>
            开始日期：
            <Servertime
              modelValue={searchValue.time_scope.start_time}
              success={(values: any) => SuccessSearchValue(values ? values : null, 'start_time')}
            />
          </div>
          <div>
            结束日期：
            <Servertime
              modelValue={searchValue.time_scope?.end_time}
              success={(values: any) => SuccessSearchValue(values ? values : null, 'end_time')}
            />
          </div>
        </div>
      ),
      extra: genExtra('time_scope')
    },
    {
      key: '6',
      label: '公司类型',
      children: (
        <ServerCheckboxList
          modelValue={searchValue.company_type}
          treeData={companyTypeTreeData}
          success={(values: any) => SuccessSearchValue(values, 'company_type')}
        />
      ),
      extra: genExtra('company_type')
    }
  ]

  const [data, setData]: any = useState([])

  const [state, setState] = useState({ width: 240 })

  const onResize = (_event: any, { size }: any) => {
    setState({ width: size.width < 150 ? 150 : size.width })
    if (size.width >= 240) {
      setCollapsed(false)
    }
  }

  const onFilterResize = (_event: any, { size }: any) => {
    setFilterState({ width: size.width < 150 ? 150 : size.width })
  }

  const toggleCollapsed = () => {
    if (!collapsed) {
      setCollapsed(true)
      setState({ width: 46 })
    } else {
      setCollapsed(false)
      setState({ width: 240 })
    }
  }

  function SuccessSearchValue(value: any, type: string) {
    //更新搜索数据的方法
    SearchData(setsearchValue, type, value)
    if (type == 'financing_round') {
      setfinancing_round(value)
    }
    //企业查询列表重置页码
    setpagination({
      current: 1,
      pageSize: 8
    })
    setData([])
  }

  //清除按钮
  function genExtra(type: string) {
    const element: any = (
      <Button
        size="small"
        onClick={() => {
          setsearchValue((prevItems: any) => {
            if (type !== 'time_scope' && type !== 'pca') return { ...prevItems, [type]: null }
            if (type === 'time_scope') {
              prevItems.time_scope = { start_time: null, end_time: null }
              return { ...prevItems }
            }
            if (type === 'pca') {
              prevItems.pca.values = []
              return { ...prevItems }
            }
          })
          // 融资阶段清除modelValue
          if (type == 'financing_round') {
            setfinancing_round([])
          }
          //企业查询列表重置页码
          setpagination({
            current: 1,
            pageSize: 8
          })
          setData([])
        }}>
        清除
      </Button>
    )

    let elementTrue: any = null

    if (searchValue[type]) {
      elementTrue = element

      if (type == 'time_scope') {
        elementTrue = searchValue[type].start_time || searchValue[type].end_time ? element : null
      }
      if (type == 'pca') {
        elementTrue = searchValue[type].values?.length ? element : null
      }
    }
    return <div>{elementTrue}</div>
  }

  const doRequest = () => {
    //loading 处理无限滚动 页码重置1
    if (loading) return
    setLoading(true)
    return IndustryChainList({
      page: pagination.current,
      page_size: pagination.pageSize,
      ...searchValue
    })
      .then((res) => {
        if (pagination.current === 1) {
          setData(res.items)
        } else {
          setData([...data, ...res.items])
        }
        if (res.total > pagination.current * pagination.pageSize) {
          setHasMore(true)
        } else {
          setHasMore(false)
        }
        setTotal(res.total)
        return res
      })
      .finally(() => {
        setLoading(false)
      })
  }

  const handleSearch = () => {
    if (
      searchValue.keywords ||
      searchValue.trade_plate?.length ||
      searchValue.company_type ||
      searchValue.time_scope.start_time ||
      searchValue.time_scope.end_time ||
      searchValue.qualified?.length ||
      searchValue.financing_round?.length ||
      searchValue.pca.values?.length
    ) {
      return true
    }
  }

  const fetchData = () => {
    setpagination({
      current: pagination.current + 1,
      pageSize: 8
    })
  }

  const actionSearchLeftList = (item: any, index: any) => {
    success(item)
    setactionindex(index)
  }

  useEffect(() => {
    doRequest()
  }, [searchValue, pagination])

  useEffect(() => {
    data && success(data[0])
  }, [data])
  return (
    <>
      <div className="p-12px">
        <HsAdminInput
          className="w-400px"
          defaultValue={searchValue.keywords}
          placeholder="请输入"
          onChange={(e: any) => setinputValue(e.target.value)}
          onPressEnter={() => SuccessSearchValue(inputValue, 'keywords')}
        />
        <Button className="ml-32px" type="primary" onClick={() => SuccessSearchValue(inputValue, 'keywords')}>
          搜索
        </Button>
      </div>
      <div className="flex h-100% IndustryChainpageSeach-box">
        <Resizable height={0} width={state.width} onResize={onResize}>
          <div style={{ width: state.width + 'px' }} className="overflow-auto boxstyle">
            <div className="h-4% datatype p-15px font-bold">企业筛选</div>
            {!collapsed && <Collapse style={{ borderRadius: 0 }} items={Collapseitems} defaultActiveKey={['1']} />}
            <Button type="primary" onClick={toggleCollapsed} className="spread-btn">
              {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            </Button>
          </div>
        </Resizable>
        <Resizable height={0} width={filterState.width} onResize={onFilterResize}>
          <div style={{ width: filterState.width + 'px' }} className="boxstyle">
            <div className="h-4% font-bold p-l-10px pt-11px">
              {`${handleSearch() ? '已找到' : '已挖掘'}${total}家${handleSearch() ? '相关' : ''}企业的供应商关系`}
            </div>
            <div id="scrollableDiv" className="max-h-780px overflow-auto">
              <InfiniteScroll
                dataLength={data.length} //This is important field to render the next data
                next={fetchData}
                hasMore={hasMore}
                loader={<h4>Loading...</h4>}
                scrollableTarget="scrollableDiv">
                <div className="mt-13px">
                  {data.length ? (
                    data.map((item: any, index: any) => (
                      <div
                        className="SearchLeftList p-5px flex"
                        style={{ background: actionindex === index ? 'rgba(0, 0, 0, 0.1)' : '' }}
                        key={index}
                        onClick={() => actionSearchLeftList(item, index)}>
                        <CompanyAvatar {...item} />
                        <div className="ml-20px">
                          <Tooltip title={item.company_name} trigger="hover">
                            <div className="font-bold truncate w-200px">{item.company_name}</div>
                          </Tooltip>
                          <div className="mt-30px flex justify-between items-center">
                            <div className="text-blue min-w-90px" onClick={() => openCompanyDetail(item.company_code)}>{`企业详情 >>`}</div>
                            <div>{`供应商数量 ：${item.supply_num} `}</div>
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <Empty />
                  )}
                </div>
              </InfiniteScroll>
            </div>
          </div>
        </Resizable>
      </div>
    </>
  )
}

export default Search
